<template>
  <div>
    <template v-if="readonly">
      <cell v-if="!list||list.length<1" value-align="left">
        <div class="black" style="width:100%;height:100%"><img src="../../assets/img/pictureupload.png" style="width:100%;height:100%"></div>
      </cell>
      <cell v-if="showOne">
        <img :height="imgHeight" :width="imgWidth" style="display:block;margin-right:5px;" :src="imgUrl[0]" />
      </cell>
      <cell-box v-else v-for="(item,index) in list" :key="index" @click.native="openFile(item)" >
        <img :height="imgHeight" :width="imgWidth" style="display:block;margin-right:5px;" :src="imgUrl[index]" />
        <!-- <span>{{item.fileName}}</span> -->
      </cell-box>
    </template>
    <div class="my-cell" style="padding: 0 30px 0 15px;" v-else>
      <div class="my-cell-title" style="width:100px">
        <span class="weui-label">{{title}}</span>
      </div>
      <div class="my-cell-content">
        <div class="show" v-for="(item,index) in list" :key="index">
          <div class="picture" :style="'backgroundImage:url('+item.url+')'"></div>
          <font-awesome-icon :icon="['fas','minus-circle']" class="photo-delete" v-show="!showPercent" @click="deletePhoto(item)" />
        </div>
        <div class="show" style="position:absolute;left:0;top:0" v-show="showPercent">
          <div class="picture mask">
            <x-circle :percent="percent" :stroke-width="6" :trail-width="6" :stroke-color="['#36D1DC', '#5B86E5']"
              trail-color="#ececec">
              <span style="color:#36D1DC">{{ percent }}%</span>
            </x-circle>
          </div>
        </div>
        <div class="show">
          <img class="picture" src="../../assets/img/add.png" @click="showMethods" />
        </div>
      </div>
    </div>
    <div v-transfer-dom>
      <popup v-model="show" is-transparent >
        <div class="photo-choice">
          <div class="photo-choice-item" @click="camera()">
            <img src="../../assets/img/camera.png" class="photo-choice-icon" />
            <div>拍照</div>
          </div>
          <div class="photo-choice-item" @click="library()">
            <img src="../../assets/img/gallery.png" class="photo-choice-icon" />
            <div>相册</div>
          </div>
          <div class="photo-choice-item" @click="audio()">
            <img src="../../assets/img/camera.png" class="photo-choice-icon" />
            <div>录音</div>
          </div>
          <div class="photo-choice-item" @click="video()">
            <img src="../../assets/img/gallery.png" class="photo-choice-icon" />
            <div>录像</div>
          </div>
        </div>
      </popup>
    </div>
  </div>
</template>

<script>
  // import Viewer from 'v-viewer'
  export default {
    name: 'photoUpload',
    props: {
      showOne:{
        type:Boolean,
        default(){
          return false
        }
      },
      imgHeight:{
        type : String,
        default : "100%"
      },
      imgWidth:{
        type : String,
        default : "60px"
      },
      title: {
        type: String,
        default: "附件"
      },
      pageToken: {
        type: String,
        required: true
      },
      fieldToken: {
        type: String,
        required: true
      },
      value: {
        type: String,
        default () {
          return ""
        }
      },
      readonly: {
        type: Boolean,
        default () {
          return false
        }
      }
    },
    data() {
      return {
        show: false,
        list: [],
        percent: 0,
        showPercent: false,
        titles: '无',
        imgUrl:[],
      }
    },
    mounted() {
      if (this.value) {
        this.getAttachment()
      }
    },
    methods: {
      showMethods() {
        this.show = true;
        this.$store.commit("CHANGE_DEFAULT_POPUP")
      },
      //拍照
      camera() {
        this.capturePhoto(Camera.PictureSourceType.CAMERA)
      },
      //图库
      library() {
        // this.capturePhoto(Camera.PictureSourceType.PHOTOLIBRARY)
        ImagePicker.getPictures((result)=> {
            result.images.forEach((item)=>{
              this.onPhotoDataSuccess(item.path)
            })
          }, (err)=> {
              // alert(err);
          }, { 
              // maximumImagesCount : 9, 
              // width : 1920, 
              // height : 1440, 
              quality : 100 
          });
      },
      //录音
      audio(){
        navigator.device.capture.captureAudio(this.onMediaSuccess, this.onFail, {duration: 15});
      },
      //录像
      video(){
        navigator.device.capture.captureVideo(this.onMediaSuccess, this.onFail, {duration: 15});
      },
      //获取照片
      capturePhoto(source) {
        navigator.camera.getPicture(this.onPhotoDataSuccess, this.onFail, {
          quality: 100,
          destinationType: device.platform == 'iOS'?Camera.DestinationType.NATIVE_URI:Camera.DestinationType.FILE_URI,
          sourceType: source,
          mediaType: Camera.MediaType.ALLMEDIA,
          targetWidth: 300, // 以像素为单位,图片比例保持不变</span>  
          targetHeight: 300 // 以像素为单位,图片比例保持不变</span>  
        });
        this.show = false;
      },

      //获取成功
      onPhotoDataSuccess(imageURL) {
        // var smallImage = document.getElementById('smallImage');
        // smallImage.style.display = 'block';
        // smallImage.src = imageURL;
        //开始上传
        this.convertImgToBase64(imageURL, (val) => {
          let obj = {
            url: val,
            id: ''
          }
          this.list.push(obj)
          // this.list.unshift(obj)
          this.showPercent = true
        })
        // alert(imageURL)
        this.upload(imageURL);
      },

      onMediaSuccess(mediaFiles) {
                  var i, path, len;
                  //遍历获取录制的文件（iOS只支持一次录制一个视频或音频）
                  for (i = 0, len = mediaFiles.length; i < len; i += 1) {
                    console.log(mediaFiles);
                     path = mediaFiles[i].fullPath;
                     alert("录制成功！\n\n"
                          + "文件名：" + mediaFiles[i].name + "\n"
                          + "大小：" + mediaFiles[i].size + "\n\n"
                          + "localURL地址：" + mediaFiles[i].localURL + "\n\n"
                          + "fullPath地址：" + path);
                  }
               },
      //拍照失败
      onFail(message) {
        //
      },

      //上传文件
      upload(fileURL) {

        //上传成功
        var success = (r) => {
          this.list[0].id = JSON.parse(r.response)[0].id
          this.showPercent = false
          this.percent = 0
        }

        //上传失败
        var fail = (error) => {
          // alert(JSON.stringify(error));
          this.showPercent = false
          this.percent = 0
        }

        var options = new FileUploadOptions();
        options.fileKey = "fileName";
        options.fileName = fileURL.substr(fileURL.lastIndexOf('/'), fileURL.lastIndexOf('?') - fileURL.lastIndexOf('/'));
        if (!options.fileName) {
          options.fileName = fileURL.substr(fileURL.lastIndexOf('/'));
        }
        options.mimeType = "application/octet-stream";
        options.httpMethod = 'POST',
          options.headers = {
            "Accept": "*/*",
            "Accept-Encoding:": "gzip, deflate",
            "Accept-Language": " zh-CN,zh;q=0.9",
            "Connection": "keep-alive",
          }
        options.chunkedMode = false,
          // 如果要传参数，写这里
          options.params = {
            Filename: fileURL.substr(fileURL.lastIndexOf('/') + 1),
            Upload: "Submit Query",
            type:"customerDownloadService",
            FixJSON:"{'_method':'streamSupportService.saveTempAttachment','_param':{pageToken:'" +
            this.pageToken + "',fieldToken:'" + this.fieldToken + "'}}"
            // modularName: 'CNL',
            // allowType: 'jpeg;jpg;png;pdf;doc;xls;xlsx;docx',
          }
        var ft = new FileTransfer();
        //注册监听上传进度
        ft.onprogress = (progressEvent) => {
          if (progressEvent)
            this.percent = Math.round(progressEvent.loaded * 100 / progressEvent.total);
        };
        // let params = "type=customerDownloadService&FixJSON={%27_method%27:%27streamSupportService.saveTempAttachment%27,%27_param%27:{pageToken:%27" +
        //   this.pageToken + "%27,fieldToken:%27" + this.fieldToken + "%27}}"
        // if(device.platform == 'iOS'){
        //   params = "type=customerDownloadService&FixJSON={'_method':'streamSupportService.saveTempAttachment','_param':{pageToken:'" +
        //     this.pageToken + "',fieldToken:'" + this.fieldToken + "'}}"
        // }
        //上传地址
        var SERVER = this.getReqUrl(this.FORM2SUBSYS_SUPPORT_URL);
        // alert(options)
        ft.upload(fileURL, SERVER, success, fail, options)
      },
      // 把图片转成base64  
      convertImgToBase64(url, callback, outputFormat) {
        var canvas = document.createElement('CANVAS'),
          ctx = canvas.getContext('2d'),
          img = new Image;
        img.crossOrigin = 'Anonymous';
        img.onload = function () {
          canvas.height = img.height;
          canvas.width = img.width;
          ctx.drawImage(img, 0, 0);
          var dataURL = canvas.toDataURL(outputFormat || 'image/png');
          callback(dataURL);
          canvas = null;
        };
        img.src = url;
      },
      deletePhoto(item) {
        let index = this.list.indexOf(item)
        alert(index)
        this.list.splice(index,1)
        this.$ajax({
          method: 'post',
          url: this.getReqUrl(this.FORM2SUBSYS_SUPPORT_URL,
            "type=customerDownloadService&FixJSON={%27_method%27:%27streamSupportService.deleteTempAttachment%27,%27_param%27:{pageToken:%27" +
            this.pageToken + "%27,fieldToken:%27" + this.fieldToken + "%27,fileName:%27" + item.id + "%27}}"),
          data: {

          }
        }).then((res) => {
          console.log(res)
          if (res.status == 200) {
          
          }else{
               this.list.splice(index,0,item)
          }
        })
      },
      //获取附件-----
      // getAttachment() {
      //   //let configs = this.row.dataconfigs?JSON.parse(this.row.dataconfigs):JSON.parse(this.row.DATACONFIGS);
      //   //let sys = configs.belongSys.toUpperCase() + '_URL'
      //   // let vText = '{"_method":"FIX_ACC_FILE_INFO.getFileWebPath","fieldToken":"' + this.value + '"}';
      //   let vText = {
      //     _method : 'streamSupportService.getAttachmentInfos',
      //     _param : [{"fieldToken":this.value}]
      //   }
      //   this.$ajax({
      //     method: 'post',
      //     // url: this[sys],
      //     url : this.COMMON_URL,
      //     data: {
      //       // FixJSON: vText
      //       FixJSON : JSON.stringify(vText)
      //     }
      //   }).then((res) => {
      //     console.log(res)
      //     this.list = res.data.attachments
      //     this.$store.commit('updateLoadingStatus', false);
      //   })

      // },
      getAttachment() {
        //let configs = this.row.dataconfigs?JSON.parse(this.row.dataconfigs):JSON.parse(this.row.DATACONFIGS);
        //let sys = configs.belongSys.toUpperCase() + '_URL'
        let vText = '{"_method":"FIX_ACC_FILE_INFO.getFileWebPath","fieldToken":"' + this.value + '"}';
        this.$ajax({
          method: 'post',
          url : this.COMMON_URL,
          data: {
            FixJSON: vText
          }
        }).then((res) => {
          console.log(res)
          this.list = res.data.data
          for(var i=0;i<this.list.length;i++){
            var url = this.list[i].FileUrl
            this.imgUrl[i] = url.replace(/a.simulate.com:8080/,"jgbim.qhfct.com:9000")
            // this.imgUrl[i] = url.replace(/a.simulate.com:8080/,"qhsz.simulate.com:8080")
            //console.log(this.imgUrl)
          }
          this.$store.commit('updateLoadingStatus', false);
        })

      },
      openFile(val) {
          this.downloadFile(val.FileUrl,val.FileName)
      },
      nofind(_this){
        _this.src="../../assets/img/no_message.png";
        _this.onerror = null;
      }
    },
    computed: {
      row() {
        return this.$store.state.currentRow
      }
    },
    watch: {
      "$store.state.defaultPop"() {
        if (!this.$store.state.defaultPop) {
          this.show = false;
        }
      },
      "value"() {
        this.getAttachment()
      }
    }
  }

</script>

<style scoped>
  * {
    margin: 0;
    padding: 0;
  }

  .show {
    width: 60px;
    /*height: 50px;*/
    overflow: hidden;
    position: relative;
    display: inline-block;
    vertical-align: middle;
    padding: 0 41px;
  }

  .picture {
    /*width: 100%;*/
    /*height: 100%;*/
    max-width: 60px;
    max-height: 60px;
    overflow: hidden;
    background-position: center center;
    background-repeat: no-repeat;
    background-size: cover;
  }

  .photo-choice {
    width: 95%;
    background-color: #fff;
    margin: 0 auto;
    border-radius: 5px;
    display: flex;
    display: -webkit-flex
  }

  .photo-choice-item {
    padding: 10px 0;
    text-align: center;
    font-size: 12px;
    flex: auto;
  }

  .photo-choice-item:active {
    background-color: #DEDEDE;
  }

  .photo-choice-icon {
    height: 60px;
  }

  .show .photo-delete {
    height: 20px;
    width: 20px;
    position: absolute;
    top: 2px;
    color: #FF4500;
    right: 0;
  }

  .mask {
    background: rgba(0, 0, 0, 0.5);
    opacity: 1;
    -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
    -webkit-transition: opacity 400ms;
    transition: opacity 400ms;
    width: 50px;
    height: 50px;
  }
</style>
